using System;
using System.Threading;

namespace Framework.Library.Core.Utils.Miscellaneous
{
    public class SingletonProvider<T> where T : class
    {
        private readonly object _lockObject = new object();
        private Creator<T> _creator;
        private T _instance;

        public SingletonProvider(Creator<T> creator)
        {
            ValidationUtils.ArgumentNotNull(creator, "creator");

            _creator = creator;
        }

        public T Value
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockObject)
                    {
                        if (_instance == null)
                        {
                            T instance = _creator();

                            if (instance == null)
                                throw new Exception("Creator delegate cannot return null.");

                            Thread.MemoryBarrier();
                            _instance = instance;
                            _creator = null;
                        }
                    }
                }

                return _instance;
            }
        }
    }
}